package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.dao.PaasFormExplainDao;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.WorkOrderExplainDao;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.sys.constant.PaasFormTableNameConstant;
import com.xbongbong.sys.domain.dao.CompanyConfigDao;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.help.SysEnvHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 吴峰
 * @date 2020/07/21 16:50
 */
@Component
public class BaseExplainModelHelp {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseExplainModelHelp.class);

    private static final List<Integer> SERVICE_PROJECT = Arrays.asList(XbbRefTypeEnum.RECEIPT_ORDER.getCode());

    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormExplainDao paasFormExplainDao;
    @Resource
    private WorkOrderExplainDao workOrderExplainDao;
    @Resource
    private CompanyConfigDao companyConfigDao;
    @Resource
    private SysEnvHelp sysEnvHelp;

    /**
     * 处理字段解释
     * @param explainList
     * @param corpid
     */
    protected void handleExplain(List<PaasFormExplainEntity> explainList, String corpid) throws XbbException {
        List<Integer> businessTypeList = new ArrayList<>();
        Long appId = 0L;
        Long menuId = 0L;
        Long formId = 0L;
        Long serviceProjectAppId = 0L;
        Long serviceProjectMenuId = 0L;
        Long serviceProjectFormId = 0L;
        for (PaasFormExplainEntity paasFormExplainEntity : explainList) {
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), paasFormExplainEntity.getSaasMark())
                    && Objects.equals("[]", paasFormExplainEntity.getExplains())) {
                Integer businessType = paasFormExplainEntity.getBusinessType();
                //默认解释缓存key："0"_businessType_distributorMark
                String key = "0" + "_" + businessType + "_" + paasFormExplainEntity.getDistributorMark();
                if (ProductConstant.HAS_SELECT_PRODUCT.contains(businessType) && Objects.equals(0L, appId)) {
                    PaasFormEntity paasFormEntity = getProductFormId(corpid);
                    formId = paasFormEntity.getId();
                    appId = paasFormEntity.getAppId();
                    menuId = paasFormEntity.getMenuId();
                }
                if (SERVICE_PROJECT.contains(businessType) &&  Objects.equals(0L, serviceProjectAppId)) {
                    PaasFormEntity paasFormEntity = paasFormModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.SERVICE_PROJECT.getCode(), corpid);
                    if (Objects.isNull(paasFormEntity)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.FORM_NOT_EXIST);
                    }
                    serviceProjectAppId = paasFormEntity.getAppId();
                    serviceProjectMenuId = paasFormEntity.getMenuId();
                    serviceProjectFormId = paasFormEntity.getId();

                }

                String explains;
                if (sysEnvHelp.isGrayEnvironment()) {
                    // 灰度环境
                    explains = paasRedisHelper.getValue(RedisPrefixConstant.GRAY_FIELD_EXPLANATION, key);
                } else {
                    // 正式环境
                    explains = paasRedisHelper.getValue(RedisPrefixConstant.FIELD_EXPLANATION, key);
                }
                if (StringUtil.isNotEmpty(explains)) {
                    explains = setProductFormId(explains, businessType, appId, formId, menuId);
                    explains = setBatchVisibleAndEditHide(businessType, explains, corpid);
                    explains = setServiceProjectFormId(explains, businessType, serviceProjectAppId, serviceProjectFormId, serviceProjectMenuId);
                    paasFormExplainEntity.setExplains(explains);
                } else {
                    businessTypeList.add(businessType);
                }
            }
        }
        if (CollectionsUtil.isNotEmpty(businessTypeList)) {

            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            params.put(StringConstant.DEL, 0);
            params.put(StringConstant.CORPID, "0");
            params.put(StringConstant.FORM_ID, 0);
            params.put("businessTypeIn", businessTypeList);
            List<PaasFormExplainEntity> initExplainList;
            if (sysEnvHelp.isGrayEnvironment()) {
                // 灰度环境
                initExplainList = paasFormExplainDao.findEntitys(params, PaasFormTableNameConstant.TB_PAAS_FORM_EXPLAIN_GRAY);
            } else {
                // 正式环境
                initExplainList = paasFormExplainDao.findEntitys(params, PaasFormTableNameConstant.TB_PAAS_FORM_EXPLAIN);
            }
            if (CollectionsUtil.isNotEmpty(initExplainList)) {
                Map<Integer, String> explainMap = new HashMap<>(initExplainList.size());
                for (PaasFormExplainEntity paasFormExplainEntity : initExplainList) {
                    Integer businessType = paasFormExplainEntity.getBusinessType();
                    //默认解释缓存key："0"_businessType_distributorMark
                    String key = "0" + "_" + businessType + "_" + paasFormExplainEntity.getDistributorMark();
                    String explains = paasFormExplainEntity.getExplains();
                    if (sysEnvHelp.isGrayEnvironment()) {
                        // 灰度环境
                        paasRedisHelper.setValue(RedisPrefixConstant.GRAY_FIELD_EXPLANATION, key, explains, TimeConstant.SECONDS_PER_DAY);
                    } else {
                        // 正式环境
                        paasRedisHelper.setValue(RedisPrefixConstant.FIELD_EXPLANATION, key, explains, TimeConstant.SECONDS_PER_DAY);
                    }
                    explains = setProductFormId(explains, businessType, appId, formId, menuId);
                    explains = setServiceProjectFormId(explains, businessType, serviceProjectAppId, serviceProjectFormId, serviceProjectMenuId);
                    explains = setBatchVisibleAndEditHide(businessType, explains, corpid);
                    explainMap.put(businessType, explains);
                }
                explainList.forEach(item->{
                    if (Objects.equals(SaasMarkEnum.SAAS.getCode(), item.getSaasMark())
                            && Objects.equals("[]", item.getExplains()) && explainMap.containsKey(item.getBusinessType())) {
                        String explains = explainMap.get(item.getBusinessType());
                        item.setExplains(explains);
                    }
                });
            }
        }
    }

    /**
     * 处理字段解释
     * @param explainList
     * @param corpid
     */
    protected void handleWorkOrderExplain(List<WorkOrderExplainEntity> explainList, String corpid) {
        List<Integer> businessTypeList = new ArrayList<>();
        Long appId = 0L;
        Long menuId = 0L;
        Long formId = 0L;
        Integer businessType = XbbRefTypeEnum.WORK_ORDER.getCode();
        try {
            for (WorkOrderExplainEntity paasFormExplainEntity : explainList) {
                if (Objects.equals("[]", paasFormExplainEntity.getExplains())) {
                    String key = "0" + "_" + businessType;
                    if (ProductConstant.HAS_SELECT_PRODUCT.contains(businessType) && Objects.equals(0L, appId)) {
                        PaasFormEntity paasFormEntity = getProductFormId(corpid);
                        formId = paasFormEntity.getId();
                        appId = paasFormEntity.getAppId();
                        menuId = paasFormEntity.getMenuId();
                    }
                    String explains;
                    if (sysEnvHelp.isGrayEnvironment()) {
                        // 灰度环境
                        explains = paasRedisHelper.getValue(RedisPrefixConstant.GRAY_FIELD_EXPLANATION, key);
                    } else {
                        // 正式环境
                        explains = paasRedisHelper.getValue(RedisPrefixConstant.FIELD_EXPLANATION, key);
                    }
                    if (StringUtil.isNotEmpty(explains)) {
                        explains = setProductFormId(explains, businessType, appId, formId, menuId);
                        paasFormExplainEntity.setExplains(explains);
                    } else {
                        businessTypeList.add(businessType);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("BaseExplainModelHelp.handleWorkOrderExplain处理工单解释出错：", e);
        }

        if (CollectionsUtil.isNotEmpty(businessTypeList)) {

            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            params.put(StringConstant.DEL, 0);
            params.put(StringConstant.CORPID, "0");
            params.put(StringConstant.FORM_ID, 0);
            List<WorkOrderExplainEntity> initExplainList = new ArrayList<>();
            if (sysEnvHelp.isGrayEnvironment()) {
                // 灰度环境
                params.put("businessType", businessType);
                List<PaasFormExplainEntity> entitys = paasFormExplainDao.findEntitys(params, PaasFormTableNameConstant.TB_PAAS_FORM_EXPLAIN_GRAY);
                initExplainList = entitys.stream().map(v -> new WorkOrderExplainEntity(corpid, 0L, 0L, 0L, v.getExplains(), v.getCreatorId(), v.getAddTime(), v.getUpdateTime(), v.getDel())).collect(Collectors.toList());
            } else {
                // 正式环境
                initExplainList = workOrderExplainDao.findEntitys(params);
            }
            if (CollectionsUtil.isNotEmpty(initExplainList)) {
                String explains = "[]";
                for (WorkOrderExplainEntity paasFormExplainEntity : initExplainList) {
                    String key = "0" + "_" + businessType;
                    explains = paasFormExplainEntity.getExplains();
                    if (sysEnvHelp.isGrayEnvironment()) {
                        // 灰度环境
                        paasRedisHelper.setValue(RedisPrefixConstant.GRAY_FIELD_EXPLANATION, key, explains, TimeConstant.SECONDS_PER_DAY);
                    } else {
                        // 正式环境
                        paasRedisHelper.setValue(RedisPrefixConstant.FIELD_EXPLANATION, key, explains, TimeConstant.SECONDS_PER_DAY);
                    }
                    explains = setProductFormId(explains, businessType, appId, formId, menuId);
                }
                for (WorkOrderExplainEntity item : explainList) {
                    if (Objects.equals("[]", item.getExplains())) {
                        item.setExplains(explains);
                    }
                }
            }
        }
    }


    /**
     * 处理非工单的字段解释
     * @param paasFormExplainEntity
     * @param corpid
     * @throws XbbException
     */
    protected void handleExplainSingle(PaasFormExplainEntity paasFormExplainEntity, String corpid) throws XbbException {
        if (Objects.nonNull(paasFormExplainEntity) && Objects.equals("[]", paasFormExplainEntity.getExplains())
                && Objects.equals(SaasMarkEnum.SAAS.getCode(), paasFormExplainEntity.getSaasMark())) {
            paasFormExplainEntity.setExplains(handleFormExplain(paasFormExplainEntity.getSaasMark(), paasFormExplainEntity.getBusinessType(), paasFormExplainEntity.getExplains(), corpid, paasFormExplainEntity.getDistributorMark()));
        }
    }

    /**
     * 处理非工单的字段解释
     * @param paasFormExplainEntity
     * @param corpid
     * @throws XbbException
     */
    protected void handleWorkOrderExplainSingle(WorkOrderExplainEntity paasFormExplainEntity, String corpid) throws XbbException {
        if (Objects.nonNull(paasFormExplainEntity) && Objects.equals("[]", paasFormExplainEntity.getExplains())) {
            paasFormExplainEntity.setExplains(handleFormExplain(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode(), paasFormExplainEntity.getExplains(), corpid, null));
        }
    }

    /**
     * 处理字段解释
     * @param saasMark
     * @param businessType
     * @param explains
     * @param corpid
     * @param distributorMark 兼容经销商模板的默认模板解释处理，工单模板该值传null（工单无经销商模板）
     * @return
     * @throws XbbException
     */
    protected String handleFormExplain(Integer saasMark, Integer businessType, String  explains, String corpid, Integer distributorMark) throws XbbException {
        if (Objects.equals("[]", explains)
                && Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
            explains = getExplainsByBusinessType(businessType, distributorMark);
            if (ProductConstant.HAS_SELECT_PRODUCT.contains(businessType)) {
                PaasFormEntity paasFormEntity = getProductFormId(corpid);
                Long formId = paasFormEntity.getId();
                Long appId = paasFormEntity.getAppId();
                Long menuId = paasFormEntity.getMenuId();
                explains = setProductFormId(explains, businessType, appId, formId, menuId);
            }
            if (SERVICE_PROJECT.contains(businessType)) {
                PaasFormEntity serviceProject = paasFormModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.SERVICE_PROJECT.getCode(), corpid);
                if (Objects.isNull(serviceProject)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.FORM_NOT_EXIST);
                }
                explains = setServiceProjectFormId(explains, businessType, serviceProject.getAppId(), serviceProject.getId(), serviceProject.getMenuId());
            }
            explains = setBatchVisibleAndEditHide(businessType, explains, corpid);
        }
        return explains;
    }

    /**
     * 根据批次保质期公司级配置开关给字段做显隐
     *
     * @param businessType 业务类型
     * @param explains 解释
     * @param corpid 公司id
     * @return 解释
     */
    private String setBatchVisibleAndEditHide(Integer businessType, String explains, String corpid) {
        if (ProductConstant.HAS_BATCH_PRODUCT.contains(businessType)) {
            List<FieldAttrEntity> fieldList = JSON.parseArray(explains, FieldAttrEntity.class);
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("configAliasIn", Arrays.asList(CompanyConfigEnum.ENABLE_BATCH_SHELF_MANAGEMENT.getAlias(), CompanyConfigEnum.ENABLE_SEQ_MANAGEMENT.getAlias()));
            param.put(ParameterConstant.CORPID, corpid);
            param.put("noLimit", 1);
            param.put("configValue", BasicConstant.IS_USE.toString());
            List<CompanyConfigEntity> batchSeqConfigList = companyConfigDao.findEntitys(param);
            if (CollectionsUtil.isNotEmpty(batchSeqConfigList)) {
                for (CompanyConfigEntity configEntity : batchSeqConfigList) {
                    if (Objects.equals(configEntity.getConfigAlias(), CompanyConfigEnum.ENABLE_BATCH_SHELF_MANAGEMENT.getAlias())) {
                        List<String> productAttrList = getProductAttrList(businessType);
                        if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                            formatExplain4BatchAffectProduct(fieldList, BasicConstant.IS_USE.toString(), productAttrList);
                        } else {
                            for (String productAttr : productAttrList) {
                                formatExplain4BatchAffectLinkProductAttr(fieldList, BasicConstant.IS_USE.toString(), productAttr);
                            }
                        }
                    } else {
                        if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                            List<String> seqFieldList = Arrays.asList(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr(), ProductEnum.SERIAL_NUMBER_MANAGEMENT.getAttr());
                            formatExplain4BatchAffectProduct(fieldList, BasicConstant.IS_USE.toString(), seqFieldList);
                        }
                    }
                }
            }
            return JSON.toJSONString(fieldList);
        }
        return explains;
    }

    /**
     * 根据是否启用显示隐藏字段
     *
     * @param enable 是否启用
     * @param fieldAttrEntity 属性
     */
    public void formatExplain4BatchSeqAffectNormalAttr(String enable, FieldAttrEntity fieldAttrEntity) {
        if (Objects.equals(enable, BasicConstant.NO_USE.toString())) {
            fieldAttrEntity.setEditHide(1);
            fieldAttrEntity.setVisible(0);
        } else {
            fieldAttrEntity.setEditHide(0);
            fieldAttrEntity.setVisible(1);
        }
    }

    /**
     * 关联产品业务影响字段
     *
     * @param fieldAttrEntityList
     * @param enable
     * @param productAttr
     */
    public void formatExplain4BatchAffectLinkProductAttr(List<FieldAttrEntity> fieldAttrEntityList, String enable, String productAttr) {
        List<String> selectProductAttrList = Arrays.asList(SelectProductEnum.BATCH.getAttr(), SelectProductEnum.GUARANTEE_PERIOD.getAttr(), SelectProductEnum.PRODUCE_DATE.getAttr(), SelectProductEnum.EXPIRE_DATE.getAttr());
        for (FieldAttrEntity fieldAttrEntity : fieldAttrEntityList) {
            if (Objects.equals(fieldAttrEntity.getAttr(), productAttr)) {
                List<FieldAttrEntity> subFieldAttrList = (List<FieldAttrEntity>)fieldAttrEntity.getSubForm().getItems();
                for (FieldAttrEntity subField : subFieldAttrList) {
                    if (selectProductAttrList.contains(subField.getAttr())) {
                        formatExplain4BatchSeqAffectNormalAttr(enable,subField);
                    }
                }
                fieldAttrEntity.getSubForm().setItems(subFieldAttrList);
            }
        }
    }

    /**
     * 产品业务影响字段
     *
     * @param fieldAttrEntityList
     * @param enable
     * @param productAttrList
     */
    public void formatExplain4BatchAffectProduct(List<FieldAttrEntity> fieldAttrEntityList, String enable, List<String> productAttrList) {
        for (FieldAttrEntity fieldAttrEntity : fieldAttrEntityList) {
            if (productAttrList.contains(fieldAttrEntity.getAttr())) {
                formatExplain4BatchSeqAffectNormalAttr(enable, fieldAttrEntity);
            }
        }
    }

    /**
     * 根据业务查找影响的字段
     *
     * @param businessType 业务类型
     * @return 属性
     */
    public List<String> getProductAttrList(Integer businessType) {
        List<String> productAttrList = new ArrayList<>();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (xbbRefTypeEnum) {
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                productAttrList.add(InstockEnum.PRODUCT.getAttr());
                break;
            case OTHER_OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
                productAttrList.add(OutstockEnum.PRODUCT.getAttr());
                break;
            case REFUND:
                productAttrList.add(RefundEnum.PRODUCTS.getAttr());
                break;
            case RETURNED_PURCHASE:
                productAttrList.add(ReturnedPurchaseEnum.PRODUCTS.getAttr());
                break;
            case INVENTORY:
                productAttrList.add(InventoryEnum.PRODUCT.getAttr());
                break;
            case TRANSFER:
                productAttrList.add(TransferEnum.PRODUCTS.getAttr());
                break;
            case ASSEMBLE:
                productAttrList.add(AssembleEnum.IN_PRODUCTS.getAttr());
                productAttrList.add(AssembleEnum.OUT_PRODUCTS.getAttr());
                break;
            case PRODUCT:
                productAttrList.add(ProductEnum.BATCH_SHELF_LIFE_MANAGEMENT.getAttr());
                productAttrList.add(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr());
                productAttrList.add(ProductEnum.SHELF_LIFE_DAYS.getAttr());
                productAttrList.add(ProductEnum.EXPIRATION_ALERT_DAYS.getAttr());
                break;
            default:
                break;
        }
        return productAttrList;
    }

    /**
     * 设置表单id、appId、menuId
     * @param explains 表单字段解释
     * @param businessType 业务类型
     * @param appId 应用id
     * @param formId 表单id
     * @param menuId 菜单id
     * @return
     */
    private String setProductFormId(String explains, Integer businessType, Long appId, Long formId, Long menuId) {
        if (ProductConstant.HAS_SELECT_PRODUCT.contains(businessType)) {
            List<FieldAttrEntity> fieldList = JSON.parseArray(explains, FieldAttrEntity.class);
            for (FieldAttrEntity item : fieldList) {
                if (Objects.equals(FieldTypeEnum.SELECT_PRODUCT.getType(), item.getFieldType())) {
                    setLinkDataInfo(item, appId, formId, menuId);
                }
            }
            return JSON.toJSONString(fieldList);
        }
        return explains;
    }

    /**
     * 设置表单id、appId、menuId
     * @param explains 表单字段解释
     * @param businessType 业务类型
     * @param appId 应用id
     * @param formId 表单id
     * @param menuId 菜单id
     * @return
     */
    private String setServiceProjectFormId(String explains, Integer businessType, Long appId, Long formId, Long menuId) {
        if (SERVICE_PROJECT.contains(businessType)) {
            List<FieldAttrEntity> fieldList = JSON.parseArray(explains, FieldAttrEntity.class);
            for (FieldAttrEntity item : fieldList) {
                if (Objects.equals(FieldTypeEnum.SELECT_SERVICE.getType(), item.getFieldType())) {
                    setLinkDataInfo(item, appId, formId, menuId);
                }
            }
            return JSON.toJSONString(fieldList);
        }
        return explains;
    }

    private void setLinkDataInfo(FieldAttrEntity item, Long appId, Long formId, Long menuId) {
        SubFormPoJo subFormPoJo = item.getSubForm();
        if (Objects.nonNull(subFormPoJo)) {
            List<? extends FieldAttrEntity> subFieldList = subFormPoJo.getItems();
            Iterator<? extends FieldAttrEntity> iterator = subFieldList.iterator();
            while (iterator.hasNext()) {
                FieldAttrEntity fieldAttrEntity = iterator.next();
                if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldAttrEntity.getFieldType())) {
                    LinkInfoPojo linkInfoPojo = fieldAttrEntity.getLinkInfo();
                    linkInfoPojo.setLinkAppId(appId);
                    linkInfoPojo.setLinkFormId(formId);
                    linkInfoPojo.setLinkMenuId(menuId);
                    break;
                }

            }
        }
    }

    /**
     * 根据类型获取字段解释
     * @param businessType
     * @return
     * @throws XbbException
     */
    private String getExplainsByBusinessType(Integer businessType, Integer distributorMark) throws XbbException{
        String corpid = "0";
        String redisKey = corpid + "_" + businessType;
        if (Objects.nonNull(distributorMark)) {
            //非工单的默认解释缓存key："0"_businessType_distributorMark
            redisKey += "_" + distributorMark;
        }
        String explains;
        if (sysEnvHelp.isGrayEnvironment()) {
            // 灰度环境
            explains = paasRedisHelper.getValue(RedisPrefixConstant.GRAY_FIELD_EXPLANATION, redisKey);
        } else {
            // 正式环境
            explains = paasRedisHelper.getValue(RedisPrefixConstant.FIELD_EXPLANATION, redisKey);
        }
        if (StringUtil.isEmpty(explains)) {
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
                if (sysEnvHelp.isGrayEnvironment()) {
                    // 灰度环境
                    Map<String, Object> param = new HashMap<>();
                    param.put(ParameterConstant.CORPID, corpid);
                    param.put(StringConstant.DEL, 0);
                    param.put(StringConstant.FORM_ID, 0);
                    param.put(ParameterConstant.BUSINESS_TYPE, businessType);
                    List<PaasFormExplainEntity> entitys = paasFormExplainDao.findEntitys(param, PaasFormTableNameConstant.TB_PAAS_FORM_EXPLAIN_GRAY);
                    if (CollectionsUtil.isEmpty(entitys)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.THIS_EXPLAIN_NOT_EXIST);
                    }
                    explains = entitys.get(0).getExplains();
                } else {
                    // 正式环境
                    WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainDao.getByFormId(0L, corpid);
                    if (Objects.isNull(workOrderExplainEntity)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.THIS_EXPLAIN_NOT_EXIST);
                    }
                    explains = workOrderExplainEntity.getExplains();
                }
            } else {
                PaasFormExplainEntity paasFormExplainEntity = null;
                if (sysEnvHelp.isGrayEnvironment()) {
                    if (Objects.nonNull(distributorMark)) {
                        //非工单的默认解释缓存key："0"_businessType_distributorMark
                        paasFormExplainEntity = paasFormExplainDao.getByBusinessType4Distributor(businessType, corpid, distributorMark, PaasFormTableNameConstant.TB_PAAS_FORM_EXPLAIN_GRAY);
                    }else {
                        paasFormExplainEntity = paasFormExplainDao.getByBusinessType(businessType, corpid, PaasFormTableNameConstant.TB_PAAS_FORM_EXPLAIN_GRAY);
                    }
                } else {
                    if (Objects.nonNull(distributorMark)) {
                        //非工单的默认解释缓存key："0"_businessType_distributorMark
                        paasFormExplainEntity = paasFormExplainDao.getByBusinessType4Distributor(businessType, corpid, distributorMark, PaasFormTableNameConstant.TB_PAAS_FORM_EXPLAIN);
                    }else {
                        paasFormExplainEntity = paasFormExplainDao.getByBusinessType(businessType, corpid, PaasFormTableNameConstant.TB_PAAS_FORM_EXPLAIN);
                    }
                }
                if (Objects.isNull(paasFormExplainEntity)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.THIS_EXPLAIN_NOT_EXIST);
                }
                explains = paasFormExplainEntity.getExplains();
            }

            if (sysEnvHelp.isGrayEnvironment()) {
                // 灰度环境
                paasRedisHelper.setValue(RedisPrefixConstant.GRAY_FIELD_EXPLANATION, redisKey, explains, TimeConstant.SECONDS_PER_DAY);
            } else {
                // 正式环境
                paasRedisHelper.setValue(RedisPrefixConstant.FIELD_EXPLANATION, redisKey, explains, TimeConstant.SECONDS_PER_DAY);
            }
            return explains;
        }
        return explains;
    }

    /**
     * 获取当前公司的产品信息
     * @param corpid
     * @return
     */
    private PaasFormEntity getProductFormId(String corpid) throws XbbException {

        Integer businessType = XbbRefTypeEnum.PRODUCT.getCode();
        String redisKey = corpid + "_" + businessType;
        String value = paasRedisHelper.getValue(RedisPrefixConstant.PRODUCT_FORM, redisKey);
        if (StringUtil.isNotEmpty(value)) {
            return JSON.parseObject(value, PaasFormEntity.class);
        }
        PaasFormEntity paasFormEntity = paasFormModel.getByBusinessTypeNoEnable(businessType, corpid);
        if (Objects.isNull(paasFormEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.FORM_NOT_EXIST);
        }
        paasRedisHelper.setValue(RedisPrefixConstant.PRODUCT_FORM, redisKey, JSON.toJSONString(paasFormEntity), TimeConstant.SECONDS_PER_DAY);
        return paasFormEntity;
    }

    /**
     * 该方法已废弃
     * Description: 获取默认解释的时候增加各自公司产品字段的属性封装
     * @param paasFormExplainEntity
	 * @param corpid
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2022/6/21 16:53
     * @since
     */
    @Deprecated
    protected void handleExplainForDefault(PaasFormExplainEntity paasFormExplainEntity, String corpid) throws XbbException {
        Integer businessType = paasFormExplainEntity.getBusinessType();
        if (ProductConstant.HAS_BATCH_PRODUCT.contains(businessType)) {
            PaasFormEntity paasFormEntity = getProductFormId(corpid);
            Long formId = paasFormEntity.getId();
            Long appId = paasFormEntity.getAppId();
            Long menuId = paasFormEntity.getMenuId();
            String explains = paasFormExplainEntity.getExplains();
            if (StringUtil.isNotEmpty(explains)) {
                explains = setProductFormId(explains, businessType, appId, formId, menuId);
                explains = setBatchVisibleAndEditHide(businessType, explains, corpid);
                paasFormExplainEntity.setExplains(explains);
            }
        }
    }
}
